//
const request = require("./request");
//--- wx.login
const wx_login = function () {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        //console.log(res);
        if (res.errMsg === 'login:ok') {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          resolve(res)
        } else {
          reject(res.errMsg)
        }
      },
      fail: err => {
        reject('wx.login失败')
      }
    })
  })
}
//--- 从后台获取openid和sesion_key
const user_getSissonkey = function (data) {
  return request.$http.call(this,{
    api:"/getSissonkey",
    data:{
      code: data.code
    }
  }).then(res=>{
    console.log(res);
    console.log(res.data);
    if (res.data.code == '1') {
      let tmpData = JSON.parse(res.data.body)
      if (!tmpData.session_key && !tmpData.openid) {
        return Promise.reject('从后台获取session_key和openid失败')
      }
      this.setData({
        'userInfo_share.session_key': tmpData.session_key,
        'userInfo_share.openid': tmpData.openid
      })
      //信息存缓存
      wx.setStorageSync('userInfo_share', this.data.userInfo_share)
      return Promise.resolve();
    } else {
      return Promise.reject('从后台获取session_key和openid失败');
    }
  }).catch(err=>{
    return Promise.reject('从后台获取session_key和openid失败');
  })
}
//--- 获取用户信息
const getUserInfoFn = function (e) {
  //console.log(e)
  if (e.detail.errMsg == 'getUserInfo:ok') {
    this.setData({
      'userInfo_share.userInfo': e.detail.userInfo
    });
    console.log(this.data.userInfo_share.userInfo);
    //信息存缓存
    wx.setStorageSync('userInfo_share', this.data.userInfo_share)
  } else {}
};
//--- 获取登录用户的后台信息
const user_loginWx = function () {
  return request.$http.call(this,{
    api:"/login",
    data:{
      appid: getApp().globalData.accountInfo.miniProgram.appId, //小程序的appId
      avatar: this.data.userInfo_share.userInfo.avatarUrl, //头像
      mobile: this.data.userInfo_share.mobile, //手机号码
      nickName: this.data.userInfo_share.userInfo.nickName, //昵称
      openid: this.data.userInfo_share.openid, //openid
    }
  }).then(res=>{
    console.log(res)
    this.setData({
      'userInfo_share.corp':res.data.body.corp||{},
      'userInfo_share.corpUser': res.data.body.corpUser||{},
      'userInfo_share.userid': res.data.body.userid||'',
      'userInfo_share.mobile': res.data.body.mobile || '',
      'userInfo_share.state': res.data.body.state||'',
      'userInfo_share.token':res.data.body.token||''
    });
    //信息存缓存
    wx.setStorageSync('userInfo_share', this.data.userInfo_share)
  }).catch(err=>{
    return Promise.reject('获取与登录用户对应的后台信息失败');
  })
}
//--- 获取用户手机号码 + 用户登录
const getPhoneNumber = function (e) {
  //console.log(e);
  return new Promise((resolve, reject) => {
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      //
      wx.showLoading({
        title: '',
        mask: true
      });
      //
      request.$http.call(this,{
        api:"/wxAES",
        data:{
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          sessionKey: this.data.userInfo_share.session_key
        }
      }).then(res=>{
        console.log(res)
        let tmpData = JSON.parse(res.data);
        //let tmpData = res.data;
        this.setData({
          "userInfo_share.mobile": tmpData.phoneNumber
        });
        //信息存缓存
        wx.setStorageSync('userInfo_share', this.data.userInfo_share);
        resolve();
      }).catch(err=>{
        reject('获取手机号码失败');
      })
    } else {

    }
  }).then(() => {
    return user_loginWx.call(this);
  }).then(() => {
    wx.hideLoading();
    const pages = getCurrentPages();
    //console.log(pages);
    if(pages[pages.length - 1].__route__==="pages/index/index"){
      //在首页登录之后---重载页面
      wx.reLaunch({
        url: '/pages/index/index',
      });
    }else{
      getApp().globalData.loginedFromOtherPage = true;
      /* 获取用户信息 */
      this.setData({
        userInfo_share: getApp().globalData.get_userInfo()
      });
      //从分享进来
      if(wx.getStorageSync('source')){
        //客户
        if (this.data.userInfo_share.state === '0') {
          //生成订单的时候用
          if(!getApp().globalData.visit_userid){
            getApp().globalData.visit_userid = wx.getStorageSync('scene')||"";
          }
          //默认销售电话 
          if(!getApp().globalData.init_sale_phone){
            getApp().globalData.init_sale_phone = wx.setStorageSync('saler_phone')||"";
          }
        }
        //员工
        if (this.data.userInfo_share.state === '1') {
          getApp().globalData.visit_userid = this.data.userInfo_share.corpUser.userid;
          getApp().globalData.init_sale_phone = this.data.userInfo_share.mobile;
        }
      }
    }
  }).catch(err => {
    console.log(err);
    wx.hideLoading();
    wx.showModal({
      title: '提示',
      content: err + '',
      showCancel: false
    })
  });
}
//
module.exports = {
  wx_login,
  user_getSissonkey,
  getUserInfoFn,
  user_loginWx,
  getPhoneNumber
};